编译器警告(等级 4)C4840

将类“type”作为可变参数函数的参数的用法不可移植

注解

传递给可变参数函数的类或结构必须是可复制的。 传递此类对象时,编译器只是执行按位复制,不会调用构造函数或析构函数。

此警告从 Visual Studio 2017 开始可用。

示例

以下示例生成 C4840,并演示如何修复此错误:

// C4840.cpp
// compile by using: cl /EHsc /W4 C4840.cpp
#include <stdio.h>

int main()
{
    struct S {
        S(int i) : i(i) {}
        S(const S& other) : i(other.i) {}
        operator int() { return i; }
    private:
        int i;
    } s(0);

    printf("%i\n", s); // warning C4840 : non-portable use of class 'main::S'
                       // as an argument to a variadic function
    // To correct the error, you can perform a static cast
    // to convert the object before passing it:
    printf("%i\n", static_cast<int>(s));
}

对于使用 CStringW 生成和管理的字符串,提供的 operator LPCWSTR() 应用于将 CStringW 对象强制转换为格式字符串所需的 C 样式字符串指针:

    CStringW str1;
    CStringW str2;
    // ...
    str1.Format("%s", static_cast<LPCWSTR>(str2));