很长一段时间以来,我认为三元运算符总是返回一个右值.但令我惊讶的是,事实并非如此.在下面的代码中,我没有看到返回值foo
和三元运算符的返回值之间的区别.
#include <iostream>
int g = 20 ;
int foo()
{
return g ;
}
int main()
{
int i= 2,j =10 ;
foo()=10 ; // not Ok
((i < 3) ? i : j) = 7; //Ok
std::cout << i <<","<<j << "," <<g << std::endl ;
}
Run Code Online (Sandbox Code Playgroud) 我不明白为什么在下面的代码中表达式C c3 = 5 + c;
不会被编译,尽管5可以转换为类型C,就像在前面的语句中一样.
#include <iostream>
class C
{
int m_value;
public:
C(int value): m_value(value) {} ;
int get_value() { return m_value; } ;
C operator+(C rhs) { return C(rhs.m_value+m_value); }
};
int main()
{
C c = 10;
C c2 = c + 5; // Works fine. 5 is converted to type C and the operator + is called
C c3 = 5 + c; // Not working: compiler error. Question: Why is 5 not …
Run Code Online (Sandbox Code Playgroud) 以下代码可在VSC ++ 2017中编译且没有任何错误,并且不会在gcc 7.3.0(error: invalid static_cast from type ‘int(int)’ to type ‘void*’
void* p = static_cast<void*>(func)
)中编译
#include <iostream>
int func(int x) { return 2 * x; }
int main() {
void* p = static_cast<void*>(func);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在下面的示例中,编译器接受static_cast
向下转换,从而导致不确定的行为,而我认为static_cast
这完全是出于安全考虑(C样式强制转换无法提供)。
#include <iostream>
class Base {
public:
int x = 10;
};
class Derived1: public Base
{
public:
int y = 20;
};
class Derived2 : public Base
{
public:
int z = 30;
int w = 40;
};
int main() {
Derived1 d1;
Base* bp1 = static_cast<Base*>(&d1);
Derived2* dp1 = static_cast<Derived2*>(bp1);
std::cout << dp1->z << std::endl; // outputs 20
std::cout << dp1->w << std::endl; // outputs random value
}
Run Code Online (Sandbox Code Playgroud) 在下面的代码中,我期望函数Foo f(Foo& x)
返回一个rvalue,令我惊讶的是它没有.所以我开始测试一些案例,找出返回值的"左值"和"rvlaueness"背后的逻辑.事实证明,返回类型为class的命名变量是左值.也许我错过了一些东西
#include <iostream>
class Foo
{
int val;
public:
Foo(int value=10)
{
val = value;
};
Foo(Foo& other)
{
std::cout << "copy ctor used" << std::endl;
val = other.val;
};
Foo(Foo&&)
{
std::cout << "move ctor used" << std::endl;
};
Foo operator=(Foo& other)
{
std::cout << "copy assign used" << std::endl;
val = other.val;
return *this;
}
Foo operator=(Foo&& a)
{
std::cout << "move assign used" << std::endl;
return *this;
}
void set(int value) { val …
Run Code Online (Sandbox Code Playgroud) 在下面的代码中,我们可以演示将小/大字符串保存在向量中时的错误(这是因为小字符串可能不会在堆上分配)。
可以说这不是标准库中的错误,而是程序员的错,因为它引用了在重新分配过程中可能消失的内容。但是作为程序员,我不应该知道数据结构的内部实现
#include<iostream>
#include<vector>
int main()
{
std::vector<std::string> v;
v.push_back("123456789abcdefg"); //bug if less than 16 characters
const char* first = v[0].c_str();
for (auto s : { "hi","guys" })
v.push_back(s);
std::cout << first << std::endl;
std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)