最近,我一直在阅读这篇文章和帖子建议停止返回const对象.Stephan T. Lavavej在2013年Going Native的演讲中也给出了这个建议.
我写了一个非常简单的测试来帮助我理解在所有这些情况下调用哪个构造函数/运算符:
这是测试:
#include <iostream>
void println(const std::string&s){
try{std::cout<<s<<std::endl;}
catch(...){}}
class A{
public:
int m;
A():m(0){println(" Default Constructor");}
A(const A&a):m(a.m){println(" Copy Constructor");}
A(A&&a):m(a.m){println(" Move Constructor");}
const A&operator=(const A&a){m=a.m;println(" Copy Operator");return*this;}
const A&operator=(A&&a){m=a.m;println(" Move Operator");return*this;}
~A(){println(" Destructor");}
};
A nrvo(){
A nrvo;
nrvo.m=17;
return nrvo;}
const A cnrvo(){
A nrvo;
nrvo.m=17;
return nrvo;}
A rvo(){
return A();}
const A crvo(){
return A();}
A sum(const A&l,const A&r){
if(l.m==0){return …Run Code Online (Sandbox Code Playgroud) 我写了以下玩具示例:
std::map<char, size_t> getMap(const std::string& s)
{
std::map<char, size_t> map;
size_t i = 0;
for (const char * b = s.data(), *end = b + s.size(); b != end; ++b)
{
map[*b] = i++;
}
return map;
}
void check(const std::string& s)
{
//The creation of the map should be thread safe according to the C++11 rules.
static const auto map = getMap("12abcd12ef");
//Now we can read the map concurrently.
size_t n = 0;
for (const char* b = s.data(), …Run Code Online (Sandbox Code Playgroud) 经过几天的痛苦调试,我可以通过这个小程序在我的单元测试中重现一个错误:
#include <iostream>
#include <vector>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <chrono>
#include <new>
int main(){
try{
for(size_t j=0;j<100;++j){
std::cout<<j<<std::endl;
std::mutex mutex;
std::unique_ptr<std::condition_variable>cv;
std::vector<std::thread>v(10);
auto wait=[&](size_t i){
std::unique_lock<std::mutex>ul(mutex);
if(!cv){cv=std::make_unique<std::condition_variable>();}
cv->wait_for(ul,std::chrono::milliseconds(i*10));
};
for(size_t i=0;i<v.size();++i){v[i]=std::thread(wait,i);}
for(size_t i=0;i<v.size();++i){v[i].join();}}}
catch(...){
std::cout<<"Exception"<<std::endl;
std::abort();}
}
Run Code Online (Sandbox Code Playgroud)
当我用lmcheck编译时:
g++-4.9.2 -lmcheck -std=c++1y -pthread /home/Arnaud/Test.cpp -o Test
Run Code Online (Sandbox Code Playgroud)
程序运行和停止 memory clobbered before allocated block
我可以在多台机器上重现这一点,并使用gcc 4.9.2和gcc 5.1.这段代码有什么问题?
注意:此代码在Visual Studio 2013中运行良好.
一些背景:我试图追踪一个导致我头痛的错误.经过许多死胡同(见这个问题)后我终于得到了这段代码:
#include <thread>
#include <vector>
#include <iosfwd>
#include <sstream>
#include <string>
#include <windows.h>
int main()
{
SRWLOCK srwl;
InitializeSRWLock(&srwl);
for(size_t i=0;i<1000;++i)
{
std::vector<std::thread>threads;
for(size_t j=0;j<100;++j)
{
OutputDebugString(".");
threads.emplace_back([&](){
AcquireSRWLockExclusive(&srwl);
//Code below modifies the probability to see the bug.
std::this_thread::sleep_for(std::chrono::microseconds(1));
std::wstringstream wss;
wss<<std::this_thread::get_id();
wss.str();
//Code above modifies the probability to see the bug.
ReleaseSRWLockExclusive(&srwl);});
}
for(auto&t:threads){t.join();}
OutputDebugString((std::to_string(i)+"\n").data());
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我在VS 2013调试器中运行此代码时,程序会挂起如下输出:
....................................................................................................0
....................................................................................................1
....................................................................................................2
...........................
Run Code Online (Sandbox Code Playgroud)
奇怪的是,如果我暂停调试器并检查发生了什么,其中一个线程在AcquireSRWLockExclusive内(在NtWaitForAlertByThreadId中)显然没有理由为什么程序挂起.当我点击继续时,程序会愉快地继续并打印更多东西,直到它再次被阻止.
你知道这里发生了什么吗?
更多信息:
我有一个如下函数,它被多次调用,这使我的程序运行缓慢.有没有办法优化它?例如,使用SIMD指令或其他技术.getray()函数用于从预先计算的查找表中检索向量-3给定向量-2查询.它在Visual-studio-2013中编译,目标配置是x64机器.
顺便说一句,使用OpenMP已经优化了多次调用此函数的for循环.
非常感谢你.
bool warpPlanarHomography(
const Eigen::Matrix3d& H_camera2_camera1
, const cv::Mat& image1
, const cv::Mat& image2
, FisheyeCameraUnified& cam1
, FisheyeCameraUnified& cam2
, const Eigen::Vector2i& patchCenter
, const int patchSize
, Eigen::Matrix<unsigned char, 7, 7>& patch1)
{
const int patchSize_2 = 3;
for (int v = 0; v < patchSize; ++v) // row
{
for (int u = 0; u < patchSize; ++u)
{
Eigen::Vector2i p1 = Eigen::Vector2i(u - patchSize_2, v - patchSize_2).cast<int>() + patchCenter;
if (p1(0, 0) < 0 …Run Code Online (Sandbox Code Playgroud) 我有一些代码需要线程安全和异常安全.下面的代码是我的问题的一个非常简化的版本:
#include <mutex>
#include <thread>
std::mutex mutex;
int n=0;
class Counter{
public:
Counter(){
std::lock_guard<std::mutex>guard(mutex);
n++;}
~Counter(){
std::lock_guard<std::mutex>guard(mutex);//How can I protect here the underlying code to mutex.lock() ?
n--;}
};
void doSomething(){
Counter counter;
//Here I could do something meaningful
}
int numberOfThreadInDoSomething(){
std::lock_guard<std::mutex>guard(mutex);
return n;}
Run Code Online (Sandbox Code Playgroud)
我有一个互斥锁,我需要锁定一个对象的析构函数.问题是我的析构函数不应该抛出异常.
我能做什么 ?
0)我不能n用原子变量替换(当然它会在这里做的但是这不是我的问题的重点)
1)我可以用旋转锁替换我的互斥锁
2)我可以尝试将锁定捕获到无限循环中,直到我最终获得锁定而没有异常引发
这些解决方案似乎都没有吸引力.你有同样的问题吗?你是怎么解决的?
我正在使用 boost-asio,我想正确处理错误消息。
在这个例子中,我打错了字(1278 而不是 127):
boost::system::error_code ec;
auto address=boost::asio::ip::address::from_string("1278.0.0.1",ec);
if(ec)
{
auto text=ec.message();
//Do Something with text but what is its encoding ?
}
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息,它似乎是在 Windows 1252 中编码的(我使用的是 Windows 7)。所以看起来编码是操作系统编码。
但是,我找不到任何说明这一事实的文件。
boost asio 中的错误消息是否使用操作系统字符集进行编码?
我遇到以下情况:
//This is Public
class B{/*usefull stuff*/};
B*f();
void g(B*b)();
//Those classes are only declared the translation unit of f and g.
class Whatever1{/*Implementation details only useful to f and g*/};
class Whatever2{/*Implementation details only useful to f and g*/};
class A{
public:
Whatever1 w1;
Whatever2 w2;
B b;
};
Run Code Online (Sandbox Code Playgroud)
在函数g中,我想将参数(指向B的指针)转换为指向A的指针.
B实例始终包含在A实例中.
我最终得到了这个:
ptrdiff_t lag(){
A a;
return (char*)&a.b-(char*)&a;}
void g(B*b){
A*a=(A*)((char*)b-lag());
//Work with a
}
Run Code Online (Sandbox Code Playgroud)
这个解决方案让我非常不舒服.
这样的偏移计算是100%正确和便携吗?
它是否以任何方式触发未定义的行为?
编辑:std :: is_standard_layout <A> ::值为1.
我有一个弹出窗口QMenu在QListView中显示很多图标:
QMenu*menu=createMenu();
QListView*list=createList();
QWidgetAction*action=new QWidgetAction(menu);
action->setDefaultWidget(list);
menu->addAction(action);
menu->show();
Run Code Online (Sandbox Code Playgroud)

有没有办法让它可以调整大小? 即我希望能够拖动弹出菜单的角落,并用鼠标调整弹出菜单的大小.我无法在谷歌或Qt文档中找到这个.
我该怎么做才能WholeProgramOptimization从CMake 启用?
这是我尝试过的:
int main(){return 0;}我创建了一个包含以下内容的C:\ Wpo\CMakeLists.txt文件:
CMAKE_MINIMUM_REQUIRED (VERSION 3.10)
PROJECT(Wpo)
ADD_EXECUTABLE(Wpo "../Wpo.cpp")
TARGET_COMPILE_OPTIONS(Wpo PRIVATE "$<$<CONFIG:Release>:/GL>")
SET_TARGET_PROPERTIES(Wpo PROPERTIES LINK_FLAGS_RELEASE "/LTCG")
Run Code Online (Sandbox Code Playgroud)我打开了一个命令行并创建了我的Visual Studio解决方案:
cd C:\Wpo\Build
cmake ..
Run Code Online (Sandbox Code Playgroud)但是当我在Visual Studio中打开我的解决方案时,没有设置整个程序优化.有趣的是WholeProgramOptimization,vcxproj文件中有一个:
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AssemblerListingLocation>Release/</AssemblerListingLocation>
<CompileAs>CompileAsCpp</CompileAs>
<ExceptionHandling>Sync</ExceptionHandling>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<Optimization>MaxSpeed</Optimization>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<WarningLevel>Level3</WarningLevel>
<WholeProgramOptimization>true</WholeProgramOptimization>
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ObjectFileName>$(IntDir)</ObjectFileName>
<DebugInformationFormat></DebugInformationFormat>
</ClCompile>
</ItemDefinitionGroup>
Run Code Online (Sandbox Code Playgroud)
如果我从项目的属性中手动选择"整个程序优化",则会在vcxproj文件的另一部分中添加一个条目:
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)
WholeProgramOptimization部分添加到错误的位置.c++ ×10
c++11 ×4
gcc ×2
boost ×1
boost-system ×1
cmake ×1
const ×1
destructor ×1
offset ×1
optimization ×1
qt ×1
qt5 ×1
raii ×1
rvo ×1
simd ×1
visual-c++ ×1