简体   繁体   English

VS2008编译的C / C ++中的struct复制问题

[英]struct copying issue in C/C++ compiled with VS2008

I have the following C/C++ code that I'm compiling with Visual Studio 2008: 我使用Visual Studio 2008编译以下C / C ++代码:

struct TEST_STRUCT{
    int nV;
    float v;

    TEST_STRUCT()
    {
        nV = 0;
        v = 0.0;
    }
};

TEST_STRUCT v1;
v1.nV = 100;
v1.v = 2.0;

const TEST_STRUCT v2;               //Making it 'const' to prevent any further changes
(TEST_STRUCT)v2 = v1;

int a = v2.nV;                      //'a' is 0, why???

Why am I getting such a strange result? 为什么我会得到如此奇怪的结果?

You just did something very nasty: you discarded your const qualifier. 您所做的事情非常讨厌:您丢弃了const限定词。

const TEST_STRUCT v2 = v1;

or 要么

const TEST_STRUCT v2(v1);

Will give you what you want... Unless you are determined to violate the const qualifier which is very, very bad. 会给您您想要的东西...除非您决心违反非常非常糟糕的const限定词。

As was pointed out, the object you tried to assign to is a temporary object while the original object remains unchanged. 如前所述,您尝试分配给的对象是一个临时对象,而原始对象保持不变。 This is one of the reasons that the compiler didn't complain. 这是编译器没有抱怨的原因之一。 If you wanted to cast the actual object you'd use some thing like this: 如果您想投射实际对象,则可以使用以下方法:

const_cast<TEST_STRUCT&>(v2) = v1;

This still won't nessecarily work because this cast result in undefined behavior when applied to an object which started its life-time as a const object: The object may live in read-only memory or the compiler may replace accesses to its members by their corresponding initial values. 这仍然无法正常工作,因为当将这种强制转换应用于作为const对象开始其生命期的对象时,这种强制转换会导致未定义的行为:该对象可能位于只读内存中,或者编译器可能会通过其成员替换对其成员的访问相应的初始值。

The only way to set members of a const object is during construction. 设置const对象成员的唯一方法是在构造过程中。 You struct conveniently has two constructors: the default constructor you declared and a copy constructor which the compiler will create for you unless it is declared or one of the subobjects (non-static members or base classes) doesn't have a copy constructor. 您的struct具有两个构造函数:您声明的默认构造函数和一个编译器将为您创建的副本构造函数,除非声明了该构造函数,否则子对象之一(非静态成员或基类)没有副本构造函数。 Thus, you'd just write: 因此,您只需编写:

TEST_STRUCT const v2(v1);

or 要么

TEST_STRUCT const v2 = v1;

In this case both calls are semantically equivalent although the latter call theoretically involves two copies. 在这种情况下,两个调用在语义上是等效的,尽管后者在理论上涉及两个副本。 If v1 has a different type the two calls are slightly different with the latter call first converting and then copying. 如果v1具有不同的类型,则这两个调用稍有不同,后一个调用先转换然后复制。 Although the copy is normally elided it would still require a copy constructor. 尽管通常会删除副本,但仍需要一个副本构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM